from Sinszm import CommonUtil
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import QWebEngineSettings, QWebEnginePage
from PyQt6.QtCore import QUrl, Qt, QLocale, QPoint,QTimer,QEvent
from PyQt6.QtWidgets import QApplication, QMainWindow, QTabWidget, QMenu, QFileDialog,QVBoxLayout, QHBoxLayout, QLabel, QPushButton,QWidget
from PyQt6.QtGui import QAction, QIcon, QPalette, QColor, QPixmap, QCursor
import sys
import os
import json


class CustomWebEngineView(QWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.dev_tools_window = None
        # 连接下载请求信号
        self.page().profile().downloadRequested.connect(self.handle_download_requested)
    
    def handle_download_requested(self, download_item):
        """处理下载请求"""
        # 获取默认下载路径（用户文档文件夹）
        default_download_path = os.path.expanduser("~")
        # 获取文件名
        file_name = download_item.downloadFileName()
        # 使用QFileDialog让用户选择保存位置
        save_path, _ = QFileDialog.getSaveFileName(
            self, "保存文件", 
            os.path.join(default_download_path, file_name)
        )
        # 如果用户选择了保存路径，则开始下载
        if save_path:
            directory = os.path.dirname(save_path)
            filename = os.path.basename(save_path)
            # 设置下载目录
            download_item.setDownloadDirectory(directory)
            # 设置下载文件名
            download_item.setDownloadFileName(filename)
            # 接受下载请求
            download_item.accept()
    
    def contextMenuEvent(self, event):
        # 创建自定义右键菜单
        menu = QMenu(self)
        menu.setStyleSheet("""
            QMenu {
                background-color: #f5f5f5;
                border: 1px solid #dcdcdc;
            }
            QMenu::item {
                /* 这是设置 QAction 在菜单中显示时的样式 */
                color: #333333;
                padding: 5px 25px 5px 20px;
                background-color: transparent;
            }
            QMenu::item:selected {
                /* 选中状态的样式 */
                color: #ffffff;
                background-color: #4a90e2;
            }
            QMenu::item:hover {
                /* 悬停状态的样式 */
                color: #ffffff;
                background-color: #4a90e2;
            }
        """)
        # 添加中文菜单项
        reload_action = QAction("刷新", self)
        reload_action.triggered.connect(lambda: self.page().triggerAction(QWebEnginePage.WebAction.Reload))
        back_action = QAction("后退", self)
        back_action.triggered.connect(lambda: self.page().triggerAction(QWebEnginePage.WebAction.Back))
        forward_action = QAction("前进", self)
        forward_action.triggered.connect(lambda: self.page().triggerAction(QWebEnginePage.WebAction.Forward))
        dev_tools_action = QAction("检查", self)
        dev_tools_action.triggered.connect(self.toggle_dev_tools)
        view_source_action = QAction("查看页面源代码", self)
        view_source_action.triggered.connect(lambda: self.page().triggerAction(QWebEnginePage.WebAction.ViewSource))
        menu.addSeparator()
        menu.addAction(back_action)
        menu.addAction(forward_action)
        menu.addAction(reload_action)
        menu.addSeparator()
        menu.addAction(dev_tools_action)
        menu.addAction(view_source_action)
        menu.addSeparator()
        # 显示菜单
        menu.exec(event.globalPos())
        
    def toggle_dev_tools(self):
        """切换开发者工具的显示状态"""
        # 检查是否已经有开发者工具窗口打开
        if self.dev_tools_window is None:
            # 创建一个新的QMainWindow作为开发者工具窗口
            self.dev_tools_window = QMainWindow()
            self.dev_tools_window.setWindowTitle("开发者工具")
            # 创建一个新的QWebEngineView来显示开发者工具
            dev_tools_view = QWebEngineView()
            # 将当前页面的调试信息发送到开发者工具视图
            self.page().setDevToolsPage(dev_tools_view.page())
            # 设置开发者工具窗口的中心部件
            self.dev_tools_window.setCentralWidget(dev_tools_view)
            # 设置窗口大小并显示
            self.dev_tools_window.resize(800, 600)
            self.dev_tools_window.show()
            # 连接窗口关闭信号，以便在关闭时重置引用
            self.dev_tools_window.destroyed.connect(lambda: setattr(self, 'dev_tools_window', None))
        else:
            # 如果窗口已经存在，切换其可见性
            if self.dev_tools_window.isVisible():
                self.dev_tools_window.hide()
            else:
                self.dev_tools_window.show()

class CustomWebEnginePage(QWebEnginePage):
    def __init__(self, parent=None, tab_widget=None):
        super().__init__(parent)
        # 保存标签页组件的引用，用于创建新标签页
        self.tab_widget = tab_widget
        self.parent_view = parent
        # 禁用自动缩放
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.ScrollAnimatorEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalStorageEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, True)
        # 设置默认字体大小为14号和默认编码为UTF-8
        self.settings().setFontSize(QWebEngineSettings.FontSize.DefaultFontSize, 12)
        self.settings().setDefaultTextEncoding("UTF-8")
        # 设置主流网站常用字体堆栈
        self.settings().setFontFamily(QWebEngineSettings.FontFamily.StandardFont, "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif,SimHei")
        self.settings().setFontFamily(QWebEngineSettings.FontFamily.SansSerifFont, "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif,SimHei")
        self.settings().setFontFamily(QWebEngineSettings.FontFamily.SerifFont, "'Noto Serif SC', 'SimSun', Georgia, 'Times New Roman', serif")
        # 启用硬件加速相关设置
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.Accelerated2dCanvasEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.WebGLEnabled, True)

    """
    拦截导航请求，处理非http/https协议的导航
    """
    def acceptNavigationRequest(self, url, navigation_type, is_main_frame):
        scheme = url.scheme()
        if scheme not in ['http', 'https'] and is_main_frame:
            QTimer.singleShot(100, self._close_current_tab)
            return True
        return super().acceptNavigationRequest(url, navigation_type, is_main_frame)
    def _close_current_tab(self):
        view = self.parent_view
        if view and self.tab_widget:
            index = self.tab_widget.indexOf(view)
            if index >= 0:
                self.tab_widget.close_tab(index)

    def createWindow(self, windowType):
        # 处理新窗口请求，在当前窗口创建新标签页而不是新窗口
        if self.tab_widget:
            new_browser = self.tab_widget.create_new_tab()
            return new_browser.page()
        # 如果没有标签页组件引用，则回退到创建新窗口
        new_window = Chrome()
        return new_window.current_browser().page()

class TabBrowser(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 设置标签页可关闭
        self.setTabsClosable(True)
        # 隐藏标签页边框
        self.setTabPosition(QTabWidget.TabPosition.North)
        self.tabBar().setDrawBase(False)
        # 连接关闭标签页信号
        self.tabCloseRequested.connect(self.close_tab)
        # 连接当前标签页变化信号
        self.currentChanged.connect(self.on_tab_changed)
        self.setStyleSheet("""
            QTabWidget {
                padding: 0px;
                border: none;
                background-color: transparent;
            }
            QTabWidget::pane {
                border: none;
                padding: 0px;
                background-color: transparent;
            }
            QTabBar {
                background-color: transparent; /* 标签栏背景色与QMainWindow一致*/
                qproperty-elideMode: ElideRight; /* 文本超出时末尾显示省略号 */
            }
            QTabBar::tab {
                background-color: #F0F8FF; /* 未选中标签页的背景色为艾利斯兰 */
                color: black; /* 标签文字颜色 */
                padding: 8px 16px; /* 标签内边距 */
                border: 1px solid #ccc; /* 标签边框 */
                border-bottom: none; /* 移除底部边框 */
                border-top-left-radius: 4px; /* 左上角圆角 */
                border-top-right-radius: 4px; /* 右上角圆角 */
                min-width: 160px; /* 设置标签最小宽度 */
                max-width: 180px; /* 设置标签最大宽度 */
            }
            QTabBar::tab:selected {
                background-color: white; /* 选中标签页的背景色也为白色 */
            }
        """)
        # 创建第一个标签页
        self.create_new_tab()

    def create_new_tab(self, url=None):
        # 创建新的QWebEngineView
        #browser = QWebEngineView()
        browser = CustomWebEngineView()
        # 创建自定义的QWebEnginePage
        page = CustomWebEnginePage(browser, self)
        browser.setPage(page)
        # 如果提供了URL则加载，否则加载默认URL
        if url:
            browser.load(QUrl(url))
        else:
            browser.load(QUrl(ReadConfig.getUrl()))
        # 连接标题变化信号到槽函数
        browser.titleChanged.connect(lambda title, index=self.count(): self.update_tab_title(index, title))
        # 添加标签页
        index = self.addTab(browser, "加载中...")
        # 切换到新标签页
        self.setCurrentIndex(index)
        return browser
    
    def close_tab(self, index):
        # 如果只剩一个标签页，则不关闭
        if self.count() <= 1:
            return
        # 获取要关闭的标签页
        browser = self.widget(index)
        # 从标签页组件中移除
        self.removeTab(index)
        # 释放资源
        browser.deleteLater()
    
    def update_tab_title(self, index, title):
        # 更新标签页标题
        self.setTabText(index, title if title else "空白页面")
        # 如果是当前标签页，同时更新窗口标题
        if index == self.currentIndex():
            window = self.window()
            if hasattr(window, 'update_window_title'):
                window.update_window_title(title)
    
    def on_tab_changed(self, index):
        # 当切换标签页时，更新窗口标题
        if index >= 0:
            browser = self.widget(index)
            window = self.window()
            if hasattr(window, 'update_window_title') and browser:
                window.update_window_title(browser.title())

class Chrome(QMainWindow):
    def __init__(self):
        super().__init__()
        self.installEventFilter(self)
        # 设置无边框窗口样式（隐藏默认标题栏）
        # FramelessWindowHint：无边框
        # WindowSystemMenuHint：启用系统菜单
        # WindowMinimizeButtonHint：启用最小化按钮
        # WindowMaximizeButtonHint：启用最大化按钮
        # WindowCloseButtonHint：启用关闭按钮
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint |
            Qt.WindowType.WindowSystemMenuHint |
            Qt.WindowType.WindowMinimizeButtonHint |
            Qt.WindowType.WindowMaximizeButtonHint |
            Qt.WindowType.WindowCloseButtonHint
        )
        self.setWindowTitle(ReadConfig.getTitle())
        self.setWindowIcon(QIcon(ReadConfig.getLogo()))
        # 尝试获取主屏幕信息（更可靠的方法）
        primary_screen = None
        # 方法1：尝试使用primaryScreen()
        if hasattr(QApplication, 'primaryScreen'):
            primary_screen = QApplication.primaryScreen()
        # 方法2：如果方法1失败，尝试从screens列表获取第一个屏幕
        if not primary_screen and hasattr(QApplication, 'screens'):
            screens = QApplication.screens()
            if screens:
                primary_screen = screens[0]
        if primary_screen:
            # 获取屏幕可用几何区域（不包括任务栏等）
            screen_geometry = primary_screen.availableGeometry()
            screen_width = screen_geometry.width()
            screen_height = screen_geometry.height()
            # 计算窗口尺寸（例如屏幕尺寸的80%）
            window_width = int(screen_width * 0.9)
            window_height = int(screen_height * 0.9)
            # 设置窗口尺寸
            self.swd = screen_width
            self.shd = screen_height
            self.wwd = window_width
            self.whd = window_height
            self.setGeometry(int((screen_width - window_width) / 2), int((screen_height - window_height) / 2), window_width, window_height)
        else:
            self.swd = 1920
            self.shd = 1080
            self.wwd = 1440
            self.whd = 800
            # 如果无法获取屏幕信息，使用默认值
            self.resize(1440, 800)
        # 保存正常状态下的窗口尺寸，以便还原时使用
        self.normal_geometry = self.geometry()
        # 创建一个垂直布局作为主布局
        self.main_layout = QVBoxLayout()
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)
        # 添加自定义标题栏和标签页浏览器到主布局
        self.create_custom_title_bar()
        # 初始化标签页浏览器
        self.tab_widget = TabBrowser(self)
        # 设置标签页浏览器为中心窗口
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.main_layout.addWidget(self.title_bar)
        self.main_layout.addWidget(self.tab_widget)
        central_widget.setLayout(self.main_layout)
        # 初始化全屏状态标志
        self.is_fullscreen = False
        # 允许窗口接收键盘事件
        self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
        # 设置窗口背景颜色为灰色
        self.setStyleSheet(f"background-color: #EEF4F9;")
        # 设置窗口背景色
        palette = self.palette()
        palette.setColor(QPalette.ColorRole.Window, QColor(238, 244, 249))
        self.setPalette(palette)
        # 显示正常窗口状态
        self.showNormal()
        
    def current_browser(self):
        # 获取当前活动的浏览器
        return self.tab_widget.currentWidget() if self.tab_widget.count() > 0 else None
    
    def create_custom_title_bar(self):
        # 创建标题栏部件
        self.title_bar = QWidget()
        self.title_bar.setFixedHeight(30)
        self.title_bar.setStyleSheet("background-color: #EEF4F9;")
        # 创建标题栏布局
        title_layout = QHBoxLayout(self.title_bar)
        title_layout.setContentsMargins(5, 0, 5, 0)
        title_layout.setSpacing(0)
        # 创建Logo标签并设置图标
        self.logo_label = QLabel()
        logo_path = ReadConfig.getLogo()  # 使用已有的获取Logo路径的方法
        logo_pixmap = QPixmap(logo_path)
        # 调整logo大小以适应标题栏
        scaled_logo = logo_pixmap.scaled(20, 20, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
        self.logo_label.setPixmap(scaled_logo)
        self.logo_label.setFixedSize(24, 24)  # 设置固定大小，留出一些边距
        # 创建窗口标题标签
        self.title_label = QLabel(ReadConfig.getTitle())
        self.title_label.setStyleSheet("color: #333;")
        # 创建刷新按钮
        self.refresh_button = QPushButton()
        self.refresh_button.setIcon(QIcon.fromTheme("window-refresh", QIcon(ReadConfig.getIcon("refresh"))))
        self.refresh_button.setFixedSize(24, 24)
        self.refresh_button.setToolTip("刷新网页")
        self.refresh_button.clicked.connect(self.refresh_current_page)
        # 最小化按钮
        self.minimize_button = QPushButton()
        self.minimize_button.setIcon(QIcon.fromTheme("window-minimize", QIcon(ReadConfig.getIcon("minimize"))))
        self.minimize_button.setFixedSize(24, 24)
        self.minimize_button.setToolTip("最小化")
        self.minimize_button.clicked.connect(self.minimize_window)
        # 最大化/还原按钮
        self.maximize_button = QPushButton()
        if not hasattr(self, 'normal_geometry'):
            self.normal_geometry = self.geometry()
        if self.isMaximized():
            self.maximize_button.setIcon(QIcon.fromTheme("window-restore", QIcon(ReadConfig.getIcon("restore"))))
            self.maximize_button.setToolTip("还原")
        else:
            self.maximize_button.setIcon(QIcon.fromTheme("window-maximize", QIcon(ReadConfig.getIcon("maximize"))))
            self.maximize_button.setToolTip("最大化")
        self.maximize_button.setFixedSize(24, 24)
        self.maximize_button.clicked.connect(self.toggle_maximize)
        # 关闭按钮
        self.close_button = QPushButton()
        self.close_button.setIcon(QIcon.fromTheme("window-closes", QIcon(ReadConfig.getIcon("close"))))
        self.close_button.setFixedSize(24, 24)
        self.close_button.setToolTip("关闭")
        self.close_button.clicked.connect(self.close)
        # 设置按钮样式
        button_style = """
            QPushButton {
                border: none;
                padding: 0px;
                background-color: transparent;
                qproperty-iconSize: 24px 24px;
            }
            QPushButton:pressed {
                background-color: rgba(160, 160, 160, 100);
                border-radius: 2px;
            }
        """
        for btn in [self.refresh_button,self.minimize_button, self.maximize_button, self.close_button]:
            btn.setStyleSheet(button_style)
        # 创建一个伸缩空间，将窗口控制按钮推到右侧
        title_layout.addWidget(self.logo_label)
        title_layout.addSpacing(5)  # 在logo和标题之间添加间距
        title_layout.addWidget(self.title_label,1)
        title_layout.addSpacing(5)
        title_layout.addWidget(self.refresh_button)
        title_layout.addSpacing(5)
        title_layout.addWidget(self.minimize_button)
        title_layout.addSpacing(5)
        title_layout.addWidget(self.maximize_button)
        title_layout.addSpacing(5)
        title_layout.addWidget(self.close_button)
        # 保存标题栏的起始拖动位置（窗口按住拖动）
        self.title_bar.mousePressEvent = self.title_bar_mouse_press_event
        # 绑定双击事件到标题栏（最大化与还原窗口）
        self.title_bar.mouseDoubleClickEvent = self.title_bar_double_click_event
        self.drag_position = QPoint()
    
    def toggle_maximize(self):
        # 切换窗口的最大化/还原状态
        if not self.isMaximized():
            # 保存当前窗口的尺寸和位置，以便还原时使用
            if not self.isFullScreen():
                self.normal_geometry = self.geometry()
            # 获取当前鼠标位置，确保最大化到当前屏幕
            screen = QApplication.screenAt(QCursor.pos())
            if screen:
                self.setGeometry(screen.geometry())
            self.showMaximized()
            self.maximize_button.setIcon(QIcon.fromTheme("window-restore", QIcon(ReadConfig.getIcon("restore"))))
            self.maximize_button.setToolTip("还原")
        else:
            # 使用showNormal()还原窗口，但为了确保生效，我们添加额外的尺寸设置
            self.showNormal()
            # 显式设置回之前保存的尺寸和位置
            if hasattr(self, 'normal_geometry'):
                # 使用QTimer延迟设置，确保showNormal()已经生效
                QTimer.singleShot(0, lambda: self.setGeometry(self.normal_geometry))
            self.maximize_button.setIcon(QIcon.fromTheme("window-maximize", QIcon(ReadConfig.getIcon("maximize"))))
            self.maximize_button.setToolTip("最大化")

    def title_bar_double_click_event(self, event):
        # 当双击标题栏时，根据窗口当前状态执行最大化或还原操作
        if event.button() == Qt.MouseButton.LeftButton:
            self.toggle_maximize()
            event.accept()

    def title_bar_mouse_press_event(self, event):
        # 记录鼠标按下的位置，用于窗口拖动
        if event.button() == Qt.MouseButton.LeftButton:
            if hasattr(self, 'windowHandle') and self.windowHandle():
                self.windowHandle().startSystemMove()
            event.accept()
    
    def minimize_window(self):
        """先还原窗口（如果是最大化状态），然后再最小化"""
        # 检查窗口是否处于最大化状态
        if self.isMaximized():
            # 如果是最大化状态，先还原窗口
            self.showNormal()
            # 显式设置回之前保存的尺寸和位置
            if hasattr(self, 'normal_geometry'):
                # 使用QTimer延迟设置，确保showNormal()已经生效
                QTimer.singleShot(50, lambda: self.setGeometry(self.normal_geometry))
            # 同样需要更新最大化按钮的状态
            self.maximize_button.setIcon(QIcon.fromTheme("window-maximize", QIcon(ReadConfig.getIcon("maximize"))))
            self.maximize_button.setToolTip("最大化")
        # 执行最小化操作
        self.showMinimized()

    def refresh_current_page(self):
        # 刷新当前活动的网页
        browser = self.current_browser()
        if browser:
            browser.page().triggerAction(QWebEnginePage.WebAction.Reload)

    # 添加事件过滤器方法
    def eventFilter(self, obj, event):
        if event.type() == QEvent.Type.WindowStateChange:
            # 处理窗口状态变化事件
            if self.isMinimized():
                # 确保窗口最小化时执行自定义逻辑
                self.minimize_window()
                return True
        return super().eventFilter(obj, event)

    def update_window_title(self, title):
        # 更新窗口标题
        #self.setWindowTitle(f"{title} - {ReadConfig.getTitle()}")
        #self.title_label.setText(f"{title} - {ReadConfig.getTitle()}")
        self.setWindowTitle(f"{ReadConfig.getTitle()} {ReadConfig.getVersion()}")
        self.title_label.setText(f"{ReadConfig.getTitle()} {ReadConfig.getVersion()}")
    
    def toggle_fullscreen(self):
        """切换窗口的全屏状态"""
        if self.is_fullscreen:
            # 退出全屏模式进入默认窗口
            self.showNormal()
            # FIXME 退出全屏模式进入最大化状态
            self.showMaximized()
            # 显示标签栏
            self.tab_widget.tabBar().setVisible(True)
            self.title_bar.setVisible(True)
            self.is_fullscreen = False
        else:
            # 进入全屏模式
            self.showFullScreen()
            # 隐藏标签栏
            self.tab_widget.tabBar().setVisible(False)
            self.title_bar.setVisible(False)
            self.is_fullscreen = True
    
    def keyPressEvent(self, event):
        """重写键盘事件处理，添加F11快捷键切换全屏"""
        if event.key() == Qt.Key.Key_F11:
            self.toggle_fullscreen()
        elif event.key() == Qt.Key.Key_F5:
            # 当按下F5键时，执行刷新操作
            self.refresh_current_page()
        else:
            super().keyPressEvent(event)

class ReadConfig:
    """
    读取配置文件
    """
    @staticmethod
    def getVal(key):
        # 获取配置文件路径，兼容PyInstaller打包环境
        if hasattr(sys, '_MEIPASS'):
            # 打包后的环境
            config_path = os.path.join(sys._MEIPASS, "res", "config.json")
        else:
            # 开发环境
            current_dir = CommonUtil.get_script_current_directory()
            config_path = os.path.join(current_dir, "res", "config.json")
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                return config.get(key, None)
        except:
            return None
    
    @staticmethod
    def getTitle():
        tit = ReadConfig.getVal("title")
        if tit:
            return tit
        else:
            return "Chrome Browser"
    
    @staticmethod
    def getVersion():
        tit = ReadConfig.getVal("version")
        if tit:
            return tit
        else:
            return "1.0.0"
    
    @staticmethod
    def getUrl():
        tit = ReadConfig.getVal("default_url")
        if tit:
            return tit
        else:
            return "https://www.sinszm.com"
    
    @staticmethod
    def getLogo():
        # 获取图标路径，兼容PyInstaller打包环境
        if hasattr(sys, '_MEIPASS'):
            # 打包后的环境，使用_MEIPASS路径
            icon_path = os.path.join(sys._MEIPASS, "res", "logo.ico")
        else:
            # 开发环境，使用当前目录
            current_dir = CommonUtil.get_script_current_directory()
            icon_path = os.path.join(current_dir, "res", "logo.ico")
        return icon_path
    
    @staticmethod
    def getIcon(name):
        # 获取图标路径，兼容PyInstaller打包环境
        if hasattr(sys, '_MEIPASS'):
            # 打包后的环境，使用_MEIPASS路径
            icon_path = os.path.join(sys._MEIPASS, "res", f"{name}.png")
        else:
            # 开发环境，使用当前目录
            current_dir = CommonUtil.get_script_current_directory()
            icon_path = os.path.join(current_dir, "res", f"{name}.png")
        return icon_path

if __name__ == "__main__":
    # 设置应用程序不受系统缩放比影响
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    QLocale.setDefault(QLocale(QLocale.Language.Chinese, QLocale.Country.China))
    app = QApplication(sys.argv)
    app.setApplicationName(ReadConfig.getTitle())
    app.setApplicationVersion(ReadConfig.getVersion())
    # 禁用自动高DPI缩放
    app.setAttribute(Qt.ApplicationAttribute.AA_Use96Dpi, True)
    # 设置应用程序样式
    app.setStyle("Fusion")
    window = Chrome()
    # 监听外部传入默认URL参数，有URL则默认打开
    url_to_open = None
    if len(sys.argv) > 1:
        url_to_open = sys.argv[1]
    if url_to_open:
        window.current_browser().setUrl(QUrl(url_to_open))
    # 监听退出
    sys.exit(app.exec())